package com.nwpu.ex2_2.Login;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录处理
 * 
 * @author liyong
 * @version 1.0
 */
@WebServlet("/Login.do")
public class Login extends HttpServlet {

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.
	 * HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws  IOException {
		// 获取数据
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		// 判断是否已经存在对应的name
		boolean judge = true;// 默认不存在
		// 将用户输入的用户名显示在终端
		System.out.println(name);
		// 获取cookies
		Cookie cookies[] = req.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				// 存在名为name的cookie
				if (cookies[i].getName().equals("name")) {
					// 重置为用户输入的用户名
					cookies[i].setValue(name);
					changeCode(res, name, password);
					judge = false;
				}
			}
		}
		// 不存在对应用户名的name cookie
		if (judge) {
			changeCode(res, name, password);
		}
		// 获取响应字符输出流，并设置content-type为html格式
		PrintWriter out = res.getWriter();
		res.setContentType("text/html;");
		// 欢迎界面
		out.println("<html>");
		out.println("<title>");
		out.println("User list");
		out.println("</title>");
		// out.println("<body><h4>User List:</h4><hr><br><br>");
		out.println("<body><h4>welcome:</h4><hr><br><br>");
		// 输出用户名
		out.println(name);
		out.println("</body>");
		out.println("</html>");
		out.close();
	}

	/**
	 * 添加或重置 cookie
	 *
	 * @param res
	 * @param name
	 * @param password
	 */
	public void changeCode(HttpServletResponse res, String name, String password) {
		Cookie c_name = new Cookie("name", name);
		Cookie c_password = new Cookie("password", password);
		// 不设置的话，则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
		c_name.setMaxAge(24 * 60 * 60);
		c_password.setMaxAge(24 * 60 * 60);
		// 发送cookie
		res.addCookie(c_name);
		res.addCookie(c_password);
	}
}